/**
 * Copyright (c) 2010 Basil Shikin, BugStat Project
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package org.bugstat.gui.wizard;

import java.awt.Component;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.swing.ButtonGroup;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;

import net.miginfocom.swing.MigLayout;

import org.bugstat.generators.ReportGenerator;
import org.bugstat.generators.ReportGeneratorComparator;
import org.bugstat.gui.UIStrings;
import org.jdesktop.swingx.JXDatePicker;
import org.pietschy.wizard.PanelWizardStep;

/**
 * This panel is used to enter bug time interval and desired diagrams. It has following layout:
 * 
 * <pre>
 *     +--------------------------+
 *     | *XPRT_ALL                |
 *     | *PICK                    |
 *     |   XPRT |FROM| TO |TO|    |
 *     |   REPORTS:               |
 *     |   +-----------------+    |
 *     |   | |0| REP_1       |    |
 *     |   | |X| REP_2       |    |
 *     |   | |X| REP_3       |    |
 *     |   +-----------------+    |
 *     +--------------------------+
 * </pre>
 * 
 * @author Basil Shikin
 */
public class SelectExportPropertiesPage extends PanelWizardStep
{
    private static final long     serialVersionUID   = -687867964685132333L;

    private final JRadioButton    exportAll;
    private final JRadioButton    exportCustom;

    private final JXDatePicker    fromDate;
    private final JXDatePicker    toDate;

    private final CheckboxList<ReportGenerator> generatorList;
    private final JPanel customExportPanel;
    
    private Date firstBugDate = null;
    private Date lastBugDate = new Date();
    private List<ReportGenerator> allGenerators = Collections.emptyList();

    public SelectExportPropertiesPage()
    {
        setName(UIStrings.TEXT_EXPORT_PROPERTIES);
        setSummary(UIStrings.TEXT_EXPORT_SUMMARY);

        exportAll = new JRadioButton(UIStrings.TEXT_EXPORT_ALL_BUGS);
        exportAll.setSelected(true);
        exportAll.addActionListener( new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                setEnabled( customExportPanel, exportCustom.isSelected() );
            }
        });
        
        exportCustom = new JRadioButton(UIStrings.TEXT_CUSTOM_EXPORT);
        exportCustom.addActionListener( new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                setEnabled( customExportPanel, exportCustom.isSelected() );
            }
        });
        
        final ButtonGroup group = new ButtonGroup();
        group.add(exportAll);
        group.add(exportCustom);

        final JLabel exportBugsFrom = new JLabel( UIStrings.TEXT_EXPORT_BUGS_FROM );
        fromDate = new JXDatePicker();
        fromDate.setFormats( "dd MMMM yyyy" );
        fromDate.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                handleFromDateChanged(fromDate.getDate());
            }
        });

        final JLabel exportBugsTo = new JLabel( UIStrings.TEXT_EXPORT_BUGS_TO  );
        toDate = new JXDatePicker(new Date());
        toDate.setFormats( "dd MMMM yyyy" );
        toDate.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                handleToDateChanged(toDate.getDate());
            }
        });
        
        final JLabel selectReportsLabel = new JLabel( UIStrings.TEXT_SELECT_REPORTS + ":" );
        generatorList = new CheckboxList<ReportGenerator>();
        final JScrollPane generatorListWrapper = new JScrollPane( generatorList );

        final JPanel exportDatesPanel = new JPanel( new MigLayout("fillx", "0[]2[]2[]0", "0[]0") );
        exportDatesPanel.add( exportBugsFrom );
        exportDatesPanel.add( fromDate );
        exportDatesPanel.add( exportBugsTo );
        exportDatesPanel.add( toDate );
        
        customExportPanel = new JPanel( new MigLayout("fill", "0[]0", "0[]7[]5[]0") );
        customExportPanel.add( exportDatesPanel, "growx, wrap");
        customExportPanel.add( selectReportsLabel, "wrap");
        customExportPanel.add( generatorListWrapper, "grow");
        setEnabled( customExportPanel, exportCustom.isSelected() );
        
        setLayout( new MigLayout("fill", "9[grow]9", "9[]9[]7[]9") );
        add( exportAll, "wrap" );
        add( exportCustom, "wrap" );
        add( customExportPanel, "gap 18, grow" );
        
        setComplete( true );
    }

    void setReportGenerators(final Collection<ReportGenerator> generators)
    {
        final List<ReportGenerator> sortedGenerators = new ArrayList<ReportGenerator>( generators.size() );
        sortedGenerators.addAll( generators );
        
        Collections.sort( sortedGenerators, new ReportGeneratorComparator() );
        setReportGenerators( sortedGenerators );
    }
    
    void setReportGenerators(final List<ReportGenerator> generators)
    {
        for ( ReportGenerator generator : generators )
        {
            generatorList.addObject( generator, generator.getName() );
        }
        
        allGenerators = generators;
    }

    void setFirstBugDate(final Date firstBugDate)
    {
        this.firstBugDate = firstBugDate; 
        
        fromDate.setDate(firstBugDate);
    }

    List<ReportGenerator> getSelectedGenerators()
    {
        if ( exportAll.isSelected() )
        {
            return allGenerators;
        }
        else
        {
            return generatorList.getSelectedObjects();
        }
    }
    
    Date getSelectedFromDate()
    {
        if ( exportAll.isSelected() )
        {
            return firstBugDate;
        }
        else
        {
            return fromDate.getDate();
        }
    }
    
    Date getSelectedToDate()
    {
        if ( exportAll.isSelected() )
        {
            return lastBugDate;
        }
        else
        {
            return toDate.getDate();
        }
    }
    
    private void handleFromDateChanged(Date date)
    {
        setComplete( date.compareTo( firstBugDate ) > 0 );
        // TODO DISPLAY ERROR MESSAGE        
    }

    private void handleToDateChanged(Date date)
    {
        setComplete( date.compareTo( lastBugDate ) < 0 );
        // TODO DISPLAY ERROR MESSAGE
    }
    
    private static void setEnabled(Container parent, boolean enabled)
    {
        // Handle trivial case
        if (parent == null) return;
        
        for ( Component child : parent.getComponents() )
        {
            child.setEnabled( enabled );
            
            if ( child instanceof Container )
            {
                setEnabled( (Container)child, enabled );
            }
        }
    }
}
